package dk.kapetanovic.jaft.transaction.fac;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;

import dk.kapetanovic.jaft.exception.TransactionException;
import dk.kapetanovic.jaft.log.Journal;
import dk.kapetanovic.jaft.log.RecoveryJournal;
import dk.kapetanovic.jaft.transaction.Transaction;
import dk.kapetanovic.jaft.transaction.TransactionImpl;
import dk.kapetanovic.jaft.transaction.TransactionManager;


public class RecoveryTransactionFactory implements TransactionFactory {
	
	private File journalDir;
	private TransactionManager tm;
	
	public RecoveryTransactionFactory(File journalDir) {
		this.journalDir = journalDir;
	}

	public RecoveryTransactionFactory(File journalDir, TransactionManager tm) {
		this.journalDir = journalDir;
		this.tm = tm;
	}

	@Override
	public Transaction createTransaction() throws TransactionException {
		File[] journals = journalDir.listFiles(new JournalFilter());
		if(journals.length == 0)
			return null;
		
		Arrays.sort(journals);
		
		try {
			Journal jo = new RecoveryJournal(journals[journals.length - 1]);
			Transaction trans = new TransactionImpl(tm, jo);
			return trans;
		} 
		catch (IOException e) {
			throw new TransactionException(e);
		} 
		catch (ClassNotFoundException e) {
			throw new TransactionException(e);
		}
	}

	@Override
	public void setTransactionManager(TransactionManager tm) {
		this.tm = tm;
	}
}
